#!/usr/bin/env python
# -*- coding: utf-8 -*-

from tornado.web import RequestHandler 
from tornado import gen
from dm_py_util import DEBUG_LOG, ERROR_LOG, BUSINESS_LOG,  WARN_LOG, INFO_LOG, SET_LOG_KEY
import time

class ErrorMessage:
    CLIENT_ERROR = {'dm_error':  499, 'error_msg': '请求参数错误'}
    SERVER_ERROR = {'dm_error':  500, 'error_msg': '内部系统错误'}
    SUCCESS = {'dm_error': 0, 'error_msg': '操作成功'}
    ILLEGAL_INPUT =  {'dm_error': 982, 'error_msg': '输入非法'}
    NO_RIGHT = {'dm_error': 600, 'error_msg': '权限错误'}
    SESSION_ERROR = {'dm_error': 602, 'error_msg': '用户session错误'}
    RESOURCE_DRAIN_ERROR = {'dm_error': 701, 'error_msg': '资源不足'}

class BaseHandler(RequestHandler):
    @gen.coroutine
    def get(self):
        SET_LOG_KEY(self.__class__.__name__)
        start_time = time.time()
        try:
            self.check_argument()
        except Exception as e:
            resp = ErrorMessage.CLIENT_ERROR
            ERROR_LOG('check argument error', e)
        else:
            resp = yield self.process()
        DEBUG_LOG('response', resp)
        self.finish(resp)
        BUSINESS_LOG('%s|%d|%f|%r' % (self.__class__.__name__, resp['dm_error'], (time.time() - start_time)* 1000, self.request.query_arguments) )
        SET_LOG_KEY('common')

    @gen.coroutine
    def post(self):
        SET_LOG_KEY(self.__class__.__name__)
        DEBUG_LOG('post', self.request.body)
        start_time = time.time()
        try:
            self.check_argument()
        except Exception as e:
            resp = ErrorMessage.CLIENT_ERROR
            ERROR_LOG('check argument error', e)
        else:
            resp = yield self.process()
        DEBUG_LOG('response', resp)
        self.finish(resp)
        BUSINESS_LOG('%s|%d|%f|%r' % (self.__class__.__name__, resp['dm_error'], (time.time() - start_time)* 1000, self.request.query_arguments) )
        SET_LOG_KEY('common')

    def check_argument(self):
        pass

    @gen.coroutine
    def process(self):
        pass


if __name__ == '__main__':
    class HelloWorldHandler(BaseHandler):
        @gen.coroutine
        def process(self):
            return {'resp': 'HelloWorld'}

    from engine import BaseHTTPServer
    s = BaseHTTPServer(HelloWorldHandler)
    s.init('/a8root/conf/live_business/server.ini')
    s.serve_forever(False)

